/*
 * Persistent storage access controller.
 *
 * @author Yves Marcoz
 *
 * Copyright(C) 2011 Yves Marcoz <yvez@marcoz.org>
 * Copyright(C) 2012 Stefan Siegl <stesie@brokenpipe.de>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 3 as
 * published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

function getDatabase() {
    return openDatabaseSync("Lukija", "1.0", "StorageDatabase", 1000000);
}

function getSetting(setting) {
    var db = getDatabase();
    var res = "";

    db.transaction(function(tx) {
        var rs = tx.executeSql('SELECT value FROM settings WHERE setting=?;', [setting]);
        if (rs.rows.length > 0) {
            res = rs.rows.item(0).value;
        } else {
            res = "Unknown";
        }
    })

    return res;
}

function setSetting(setting, value) {
    var db = getDatabase();
    var res = "";

    db.transaction(function(tx) {
        var rs = tx.executeSql('INSERT OR REPLACE INTO settings VALUES (?,?);', [setting,value]);
        if (rs.rowsAffected > 0) {
            res = "OK";
        } else {
            res = "Error";
        }
    });

    return res;
}

function getRilArticle(url) {
    var db = getDatabase();
    var res = "";

    db.transaction(function(tx) {
        var rs = tx.executeSql('SELECT article FROM rilArticles WHERE url=?;', [url,]);
        if (rs.rows.length > 0) {
            res = rs.rows.item(0).article;
        } else {
            res = "Unknown";
        }
    });

    return res;
}

function getRilTitle(url) {
    var db = getDatabase();
    var res = "";

    db.transaction(function(tx) {
        var rs = tx.executeSql('SELECT title FROM rilArticles WHERE url=?;', [url,]);
        if (rs.rows.length > 0) {
            res = rs.rows.item(0).title;
        } else {
            res = "Unknown";
        }
    });

    return res;
}

function getListOfDownloadables() {
    var db = getDatabase();
    var res;

    db.transaction(function(tx) {
        res = tx.executeSql('SELECT url FROM rilArticles WHERE downloaded=0;');
    });

    return res
}

function getListOfEmptyTitleArticles() {
    var db = getDatabase();
    var res;

    db.transaction(function(tx) {
        res = tx.executeSql("SELECT url FROM rilArticles WHERE title='';");
    });

    return res
}

function setRilTitle(url, title) {
    var db = getDatabase();
    var res;

    db.transaction(function(tx) {
        var rs = tx.executeSql('UPDATE rilArticles SET updateTime = date(\'now\'), title = ? ' +
                               'WHERE url = ?', [title, url]);

        if (rs.rowsAffected > 0) {
            res = "OK";
        } else {
            res = "Error";
        }
    });

    return res;
}


function saveRilArticle(url, title, article, unread) {
    var db = getDatabase();
    var res;

    db.transaction(function(tx) {
        var rs;

        rs = tx.executeSql('SELECT COUNT(*) AS num FROM rilArticles WHERE url=?', [url]);
        if (+rs.rows.item(0).num) {
            /* the article is already present in our database, do update. */
            rs = tx.executeSql('UPDATE rilArticles SET updateTime = date(\'now\'), unread = ? ' +
                               'WHERE url = ?', [unread, url]);
        } else {
            /* new article, do insert. */
            rs = tx.executeSql('INSERT INTO rilArticles VALUES (?,?,?,?,0,date(\'now\'));', [url, title, article, unread]);
        }

        if (rs.rowsAffected > 0) {
            res = "OK";
        } else {
            res = "Error";
        }
    });

    return res;
}

function markRilArticleAsRead(url) {
    var db = getDatabase();
    var res = "";

    db.transaction(function(tx) {
        var rs = tx.executeSql('UPDATE rilArticles SET unread=1 WHERE url=?', [url]);
        if (rs.rowsAffected > 0) {
            res = "OK";
        } else {
            res = "Error";
        }
    });

    return res;
}

function getListOfReadArticles() {
    var db = getDatabase();
    var res;

    db.transaction(function(tx) {
        res = tx.executeSql("SELECT url FROM rilArticles WHERE unread=1;");
    });

    return res
}

function removeReadArticles() {
    var db = getDatabase();
    var res;

    db.transaction(function(tx) {
        res = tx.executeSql("DELETE FROM rilArticles WHERE unread=1;");
    });
}


function updateRilArticle(url, article) {
    var db = getDatabase();
    var res = "";

    db.transaction(function(tx) {
        var rs = tx.executeSql('UPDATE rilArticles SET article=? WHERE url=?;', [article,url]);

        if (rs.rowsAffected > 0) {
            res = "OK";
            tx.executeSql('UPDATE rilArticles SET downloaded=1 WHERE url=?;',[url]);
        } else {
            res = "Error";
        }
    });

    return res;
}

function getRilList(listmodel) {
    var db = getDatabase();
    var i;

    db.transaction(function(tx) {
        var rs = tx.executeSql('SELECT url,title,unread,downloaded FROM rilArticles ORDER BY updateTime');

        if (rs.rows.length > 0) {
            //listmodel.clear();
            var indexedList = [];
            for(i = 0; i < listmodel.count; i++) {
                indexedList[i] = listmodel.get(i).articleid;
            }

            for(i = 0; i < rs.rows.length; i++) {
                var index = indexedList.indexOf(rs.rows.item(i).url);
                if (index > -1) {
                    listmodel.setProperty(index, "unread", rs.rows.item(i).unread);
                    listmodel.setProperty(index, "title", rs.rows.item(i).title);
                } else {
                    listmodel.append({title: rs.rows.item(i).title, articleid: rs.rows.item(i).url, unread: rs.rows.item(i).unread, downloaded: rs.rows.item(i).downloaded});
                }
            }
        } else {
            //xml = "Error";
        }
    });

    return listmodel;
}



function resetAll() {
    var db = getDatabase();

    db.transaction(function(tx) {
        tx.executeSql('DROP TABLE rilArticles;');
        tx.executeSql('DROP TABLE settings;');
        initialize();
    });
}

function initialize() {
    var db = getDatabase();

    db.transaction(function(tx) {
        // Create the database if it doesn't already exist
        tx.executeSql('CREATE TABLE IF NOT EXISTS settings(setting TEXT UNIQUE, value TEXT)');
        tx.executeSql('CREATE TABLE IF NOT EXISTS rilArticles(url TEXT UNIQUE, title TEXT, article TEXT, unread INTEGER, downloaded INTEGER, updateTime TEXT)');
        tx.executeSql('CREATE TABLE IF NOT EXISTS feeds(feeid TEXT UNIQUE,title TEXT, url TEXT)')
    });
}
